import RPi.GPIO as GPIO
import time

colors=[0xff00,0x00ff,0x0ff0,0xf00f]
makerobo_pins=(11,12)   #pin管脚字典

GPIO.setmode(GPIO.BOARD)    #采用物理编号
GPIO.setwarnings(False)     #去除GPIO的警告
GPIO.setup(makerobo_pins,GPIO.OUT)     #列表中都为out
GPIO.output(makerobo_pins,GPIO.LOW)     #pin都为low


p_R = GPIO.PWM(makerobo_pins[0],2000)   #设置频率2khz
p_G = GPIO.PWM(makerobo_pins[1],2000)   #设置频率2khz

#初始化占空比为0
p_R.start(0)
p_G.start(0)

def makerobo_pwm_map(x,in_min,in_max,out_min,out_max):
    return (x-in_min)*(out_max-out_min)/(in_max-in_min) + out_min

def makerobo_set_color(col):
    R_val = col>>8
    G_val = col & 0xff
    #把0-255范围同比例缩小到 0-100 之间
    R_val = makerobo_pwm_map(R_val,0,255,0,100)
    G_val = makerobo_pwm_map(G_val, 0, 255, 0, 100)

    p_R.ChangeDutyCycle(R_val)
    p_G.ChangeDutyCycle(G_val)

def loop():
    while True:
        for col in colors:
            makerobo_set_color(col)
            time.sleep(0.5)

def destroy():
    p_R.stop()
    p_G.stop()
    GPIO.cleanup()  #释放资源

if __name__=='__main__':
    try:
        loop()
    except KeyboardInterrupt:   #按下 ctrl+c 释放资源
        destroy()